package musicstore.com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {
	protected Connection conn = null;
	protected PreparedStatement stmt = null;
	protected ResultSet rs = null;
	
	public void openConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/musicstore","root","123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public int executeUpdate(String sql, Object[] parameters) throws SQLException{
		stmt = conn.prepareStatement(sql);
		if(parameters != null){
			for(int i=0; i<parameters.length; i++){
				stmt.setObject(i+1, parameters[i]);
			}
		}
		return stmt.executeUpdate();
	}
	
	public ResultSet executeQuery(String sql, Object[] parameters) throws SQLException{
		stmt = conn.prepareStatement(sql);
		if(parameters != null){
			for(int i=0; i<parameters.length; i++){
				stmt.setObject(i+1, parameters[i]);
			}
		}
		rs = stmt.executeQuery();
		return rs;
	}
	
	public void closeResource(){
		try {
			if(rs!=null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(stmt!=null)
				stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
